import { app, shell, BrowserWindow, ipcMain, screen } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

// 在createWindow函数中添加IPC监听
function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 200,
    height: 200,
    show: false,
    autoHideMenuBar: true,
    frame: false, // 保持无边框
    transparent: true,
    alwaysOnTop: true,
    resizable: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: false,
      contextIsolation: true
    }
  })

  // 边界限制和多屏支持函数
  const constrainWindowToBounds = (): void => {
    if (mainWindow.isDestroyed()) return // 添加窗口销毁检查

    const windowBounds = mainWindow.getBounds()
    const displays = screen.getAllDisplays()

    // 找到包含窗口的显示器
    let targetDisplay = screen.getDisplayNearestPoint({
      x: windowBounds.x + windowBounds.width / 2,
      y: windowBounds.y + windowBounds.height / 2
    })

    // 如果窗口完全在所有显示器外，使用主显示器
    const isWindowInAnyDisplay = displays.some((display) => {
      const bounds = display.bounds
      return (
        windowBounds.x < bounds.x + bounds.width &&
        windowBounds.x + windowBounds.width > bounds.x &&
        windowBounds.y < bounds.y + bounds.height &&
        windowBounds.y + windowBounds.height > bounds.y
      )
    })

    if (!isWindowInAnyDisplay) {
      targetDisplay = screen.getPrimaryDisplay()
    }

    const displayBounds = targetDisplay.bounds
    let newX = windowBounds.x
    let newY = windowBounds.y

    // 限制窗口不能超出显示器边界
    if (windowBounds.x < displayBounds.x) {
      newX = displayBounds.x
    } else if (windowBounds.x + windowBounds.width > displayBounds.x + displayBounds.width) {
      newX = displayBounds.x + displayBounds.width - windowBounds.width
    }

    if (windowBounds.y < displayBounds.y) {
      newY = displayBounds.y
    } else if (windowBounds.y + windowBounds.height > displayBounds.y + displayBounds.height) {
      newY = displayBounds.y + displayBounds.height - windowBounds.height
    }

    // 如果位置需要调整，则移动窗口
    if (newX !== windowBounds.x || newY !== windowBounds.y) {
      mainWindow.setPosition(newX, newY)
    }
  }

  // 监听窗口移动事件
  mainWindow.on('move', () => {
    constrainWindowToBounds()
  })

  // 监听显示器配置变化
  screen.on('display-added', () => {
    constrainWindowToBounds()
  })

  screen.on('display-removed', () => {
    constrainWindowToBounds()
  })

  screen.on('display-metrics-changed', () => {
    constrainWindowToBounds()
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    // 初始位置检查
    constrainWindowToBounds()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // 添加窗口拖动IPC处理
  ipcMain.handle('start-drag', () => {
    return { success: true }
  })

  // 优化的拖动处理
  ipcMain.handle('drag-window', (_, { deltaX, deltaY }) => {
    try {
      const bounds = mainWindow.getBounds()
      const newX = bounds.x + deltaX
      const newY = bounds.y + deltaY

      // 获取当前显示器信息，正确处理DPI缩放
      const currentDisplay = screen.getDisplayNearestPoint({
        x: bounds.x + bounds.width / 2,
        y: bounds.y + bounds.height / 2
      })

      // 使用display.bounds而不是workAreaSize，确保坐标系统一致
      const displayBounds = currentDisplay.bounds
      // const scaleFactor = currentDisplay.scaleFactor

      // 边界检测（考虑DPI缩放）
      const clampedX = Math.max(
        displayBounds.x,
        Math.min(newX, displayBounds.x + displayBounds.width - bounds.width)
      )
      const clampedY = Math.max(
        displayBounds.y,
        Math.min(newY, displayBounds.y + displayBounds.height - bounds.height)
      )

      mainWindow.setBounds({
        x: clampedX,
        y: clampedY,
        width: bounds.width,
        height: bounds.height
      })

      return { success: true }
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : String(error) }
    }
  })

  ipcMain.handle('stop-drag', () => {
    return { success: true }
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
